// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
    // const wxContext = cloud.getWXContext()
    console.log(event);
    const {
        id
    } = event;
    if(!id) return new Error('缺少ID')
    const missionTarget = await db.collection('mission').doc(id).get().then(res => res.data);
    if (missionTarget.back && missionTarget.back.length) {
        return {
            errMeg: 'could not delete cause back is not empty'
        }
    }
    const promiseList = [];
    //删除前置任务索引
    for (const item of missionTarget.front) {
        promiseList.push(
            new Promise((resolve, reject) => {
                db.collection('mission').doc(item).field({ back: true }).get()
                    .then(res => res.data.back)
                    .then(back => {
                        if(!back||!back.length) {
                            resolve();
                            return;
                        }
                        const index = back.indexOf(id);
                        if (index >= 0) {
                            back.splice(index, 1);
                            db.collection('mission').doc(item).update({
                                data: { back: db.command.set(back) }
                            })
                                .then(resolve)
                                .catch(resolve)
                        }else{
                            resolve();
                        }
                    })
                    .catch(resolve)
            })
        )
    }
    //删除任务历史记录
    promiseList.push(db.collection('missionLog').where({
        missionId:id
    }).remove())
    //删除任务
    await Promise.all(promiseList);
    return await db.collection('mission').doc(id).remove()
}